using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace JwtBearerAuthor
{
    public class Startup
    {
        private readonly string issurer = "JWTBearer.Auth"; //发行人
        private readonly string audience = "api.auth"; //受众人
        private readonly string secretCredentials = "2691894sc2691894sc"; //密钥

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAuthentication(e =>
            {
                e.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                e.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(e => 
            {
                e.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true, // 是否验证发行人
                    ValidIssuer = this.issurer, // 发行人
                    ValidateAudience = true, // 是否验证受众人
                    ValidAudience = this.audience, // 受众人
                    ValidateIssuerSigningKey = true, // 是否验证密钥
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(this.secretCredentials)),
                    ValidateLifetime = true, // 验证生命周期
                    RequireExpirationTime = true, // 需要过期时间
                };
            });
            services.AddAuthorization(e =>
            {
                e.AddPolicy("policy1", e => e.RequireRole("admin"));
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseAuthentication();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}